<?php
	require_once 'base.dao.php';
	require_once 'user.vao.php';
	require_once 'company.dao.php';
	
	class UserManager extends BaseManager {	
		public function login ($email, $pass) {
			$query = sprintf("select * from users where email = '%s' and password = '%s'",
						   mysql_real_escape_string($email),
						   md5(mysql_real_escape_string($pass)));
			try {
				$result = $this->executeQuery($query);
				if (count($result) == 0)
					return null;
				extract($result[0]);
				return new User($id,
								$name,
								$email,
								$password,
								$active,
								$group_id);
			} catch (QueryException $e) {
				return null;
			}
		}
		
		public function getUserById ($userId) {
			$query = sprintf("select * from users where id = %d",
							 $userId);
			try {
				$result = $this->executeQuery($query);
				if (count($result) > 0) {
					extract($result[0]);
					return new User($id,
									$name,
									$email,
									$password,
									$active,
									$group_id);
				}
				return null;
			} catch (QueryException $e) {
				return null;
			}
		}
		
		public function getUserCompany ($userId) {
			$user = $this->getUserById($userId);
			if (!is_null($user)) {
				$query = sprintf("select co.* from companies co inner join groups gr on co.id = gr.company_id where gr.company_id = %d",
								 $user->getGroupId());
				$result = $this->executeQuery($query);
				if (count($result) > 0) {
					extract($result[0]);
					return new Company($id,
									   $name,
									   $address,
									   $phone,
									   $fax,
									   $email);
				}
				return null;
			}
			return null;
		}

                public function setPermisos($permisos){
                    $menus = $this->executeQuery("SELECT * FROM menus ORDER BY name");
                    $file = str_replace("/", "", $_SERVER['PHP_SELF']);
                    foreach($menus as $menu){
                        $funciones_encontradas = $this->executeQuery("SELECT * FROM functions WHERE menu_id=".$menu['id']." AND mask&$permisos ORDER BY archivo");
                        foreach($funciones_encontradas as $funcion){
                            $funciones[$menu['name']][]=$funcion;
                        }
                    }
                    $_SESSION['funciones']=$funciones;
                }
	}
?>